package com.spring.boot.standard.admin.controller;

import java.io.File;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import com.spring.boot.standard.admin.common.beans.PageData;
import com.spring.boot.standard.admin.common.CommonController;
import com.spring.boot.standard.admin.common.beans.CommonResult;
import com.spring.boot.standard.admin.entity.Roadmaps;
import com.spring.boot.standard.admin.service.RoadmapsService;

/**
 * @author qinhao
 * @since Tue Oct 12 16:21:55 CST 2021
 */
@RestController
@RequestMapping("/roadmaps")
@Api(value="里程碑接口",tags={"roadmaps(里程碑)接口"})
public class RoadmapsController extends CommonController {

	@Value("${web.user-data-path}")
	private String userDataPath;

    @Autowired
    RoadmapsService roadmapsService;

	@ApiOperation(value = "获取分页数据" ,notes = "获取分页数据" )
	@ApiImplicitParams({
		@ApiImplicitParam(name = "key" ,value = "搜索关键字名称" , required = false, dataType = "String"),
		@ApiImplicitParam(name = "keywords" ,value = "搜索关键字内容" , required = false, dataType = "String"),
		@ApiImplicitParam(name = "projectname" ,value = "所属项目" , required = false, dataType = "String")
	})
    @RequestMapping(value = "/pagedata", method = { RequestMethod.GET  })
	public PageData<Roadmaps> pagedata(Pageable pageable,String key,String keywords,String projectname){
		return convertPage(roadmapsService.findAll(pageable,new Object[]{key,keywords,projectname}));
	}

	@ApiOperation(value = "获取单条数据对象" ,notes = "获取单条数据对象")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query",name = "roadmapsid" ,value = "里程碑ID" , required = true, dataType = "String")
	})
	@RequestMapping(value = "/singledata" ,method = { RequestMethod.GET })
	public Roadmaps singledata(String roadmapsid){
		return roadmapsService.findById(roadmapsid);
	}

	@ApiOperation(value = "删除里程碑", notes = "删除里程碑" )
		@ApiImplicitParams({ @ApiImplicitParam(name = "ids", value = "ID拼接的字符串", required = true, dataType = "String")
	})
	@RequestMapping(value = "/delete" ,method = { RequestMethod.DELETE})
	public CommonResult delete(String ids) {
		try {
			String[] id_array = ids.split(",");
			for(String roadmapsid:id_array){
				roadmapsService.deleteById(roadmapsid);
			}
			cr = new CommonResult(true,0,null,"删除成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cr;
	}

	@ApiOperation(value = "保存里程碑", notes = "保存里程碑,id列为空则为新增,不为空则为修改")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "Roadmaps",value = "里程碑",required = false,dataType = "Roadmaps")
	})
	@RequestMapping(value = "/save" ,method = { RequestMethod.POST })
	public CommonResult save(@RequestParam(value="fileofpic", required=false) MultipartFile fileofpic,
							 @RequestParam(value="fileofzip", required=false) MultipartFile fileofzip,Roadmaps roadmaps) {
		try {
			//id是空字符串的时候  JPA保存后不返回32位的新ID 所以这里特殊处理一下
			if(roadmaps.getRoadmapsid()!=null && roadmaps.getRoadmapsid().equals("")){
				roadmaps.setRoadmapsid(null);
			}
			roadmapsService.save(roadmaps);
			File fileDir = new File(userDataPath + "/roadmaps/");
			if(!fileDir.exists()) {
				//如果没有目录应该创建目录
				fileDir.mkdirs();
			}
			if(fileofpic!=null && !fileofpic.isEmpty()) {
				String file_name = roadmaps.getRoadmapsid() + fileofpic.getOriginalFilename().substring(fileofpic.getOriginalFilename().lastIndexOf("."));
				String file_path = userDataPath + "/roadmaps/" + file_name;
				// /home/data...被认为是相对路径了   这里处理一下明确为绝对路径
				File dest = new File(new File(file_path).getAbsolutePath());
				fileofpic.transferTo(dest);
				roadmaps.setPicture("roadmaps/"+file_name);
			}
			if(fileofzip!=null && !fileofzip.isEmpty()) {
				String file_name = roadmaps.getRoadmapsid() + fileofzip.getOriginalFilename().substring(fileofzip.getOriginalFilename().lastIndexOf("."));
				String file_path = userDataPath + "/roadmaps/" + file_name;
				// /home/data...被认为是相对路径了   这里处理一下明确为绝对路径
				File dest = new File(new File(file_path).getAbsolutePath());
				fileofzip.transferTo(dest);
				roadmaps.setZipfile("roadmaps/"+file_name);
			}
			roadmapsService.save(roadmaps);
			cr = new CommonResult(true,0,null,"保存成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return   cr;
	}

	@ApiOperation(value = "签到", notes = "签到,证明已接收里程碑消息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "Roadmaps",value = "里程碑",required = false,dataType = "Roadmaps")
	})
	@RequestMapping(value = "/sign" ,method = { RequestMethod.POST })
	public CommonResult sign(Roadmaps roadmaps) {
		try {			Roadmaps exist_rm = roadmapsService.findById(roadmaps.getRoadmapsid());
			exist_rm.setThetime(new Timestamp(new Date().getTime()));
			exist_rm.setParticipants(roadmaps.getParticipants());
			exist_rm.setSignstatus(roadmaps.getSignstatus());
			roadmapsService.save(exist_rm);
			cr = new CommonResult(true,0,null,"更新成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return   cr;
	}

	@ApiOperation(value = "导出数据", notes = "导出数据")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "key" ,value = "搜索关键字名称" , required = false, dataType = "String"),
			@ApiImplicitParam(name = "keywords" ,value = "搜索关键字内容" , required = false, dataType = "String")
	})
	@RequestMapping(value = "/exports", method = { RequestMethod.GET  })
	public ResponseEntity<byte[]> exports( Pageable pageable,String key,String keywords) {
		ResponseEntity<byte[]> entity = null;
		String[] titleNameArray = {"时间节点@时间节点","内容描述@内容描述","参与人@参与人","截图@截图","压缩包@用于下载压缩包","创建人@创建人","序号@序号","确认状态@确认状态","项目名称@项目名称"};
		String[] fieldNameArray = {"thetime","content","participants","picture","zipfile","creator","sn","signstatus","projectname"};
		try {
			//根据条件获取数据
			List<Roadmaps> data = roadmapsService.findAll(pageable,new Object[]{key,keywords}).getContent();
			//数据转换成流并导出

			InputStream is = super.exportExcelContent(data,titleNameArray,fieldNameArray);
			byte[] body = new byte[is.available()];
			is.read(body);
			HttpHeaders headers = new HttpHeaders();
			String exportFilename = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date()) + ".xls";
			headers.add("Content-Disposition", "attchement;filename=" + exportFilename);
			HttpStatus statusCode = HttpStatus.OK;
			entity = new ResponseEntity<byte[]>(body, headers, statusCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return entity;
	}

	@ApiOperation(value = "导入里程碑", notes = "导入里程碑")
    @RequestMapping(value = "/imports", method = { RequestMethod.POST })
	public CommonResult imports(@RequestParam("file") MultipartFile file) {
		int imp_num = 0;
		//如果文件不为空，写入上传路径
		try {
			if(!file.isEmpty()) {
				String[] fieldNameArray = {"thetime","content","participants","picture","zipfile","creator","sn","signstatus","projectname"};
				List<Map<String,String>> list = super.getExcelContent(file, fieldNameArray);
                imp_num =  roadmapsService.saveFromList(list);
				cr = new CommonResult(true,0,null,"导入成功，导入数据："+imp_num+"条！");
			} else {
				cr = new CommonResult(false,500,null,"文件上传失败！");
			}
		} catch (Exception e) {
			cr = new CommonResult(false,500,null,super.getPointOfException(e.getMessage()));
		}
		return  cr;
	}

}